import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.java_websocket.*;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class MyWebSocket extends WebSocketServer {
	private static int serverPort = 9999;
	private static int counter = 0;
	private static ServerSocket serverSocket;
	
	// 用串列來儲存每個client
	private static ArrayList<Socket> players = new ArrayList<Socket>();
	
	public MyWebSocket() throws UnknownHostException {
		super();
	}
	
	public MyWebSocket( int port ) throws UnknownHostException {
		super( new InetSocketAddress( port ) );
	}
	
	public MyWebSocket( int port , Draft d ) throws UnknownHostException {
		super( new InetSocketAddress( port ), Collections.singletonList( d ) );
	}
	
	public MyWebSocket( InetSocketAddress address, Draft d ) {
		super( address, Collections.singletonList( d ) );
	}
	
	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		WebSocketImpl.DEBUG = false;
		int port;
		try {
			//port = new Integer( args[ 0 ] );
			//指定這個port
			port = serverPort;
		} catch ( Exception e ) {
			System.out.println( "No port specified. Defaulting to 9003" );
			port = 9003;
		}
		//new MyWebSocket( port, new Draft_17() ).start();
		//開啟伺服器
		MyWebSocket sv = new MyWebSocket( port );
		sv.start();
		System.out.println( "ChatServer started on port: " + sv.getPort() );
		//讀取WebSocket的資料進來
		BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) );
		while ( true ) {
			String in = sysin.readLine();
			sv.sendToAll( in );
			if( in.equals( "exit" ) ) {
				sv.stop();
				break;
			} else if( in.equals( "restart" ) ) {
				sv.stop();
				sv.start();
				break;
			}
		}
	}

	@Override
	public void onOpen( WebSocket conn, ClientHandshake handshake ) {
		counter++;
		System.out.println( "Opened connection number" + counter );
		conn.send("Hi,This is my WebSocket Server!~");
	}

	@Override
	public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
		System.out.println( "closed" );
	}

	@Override
	public void onError( WebSocket conn, Exception ex ) {
		System.out.println( "Error:" );
		ex.printStackTrace();
	}
	//當訊息進來的時後，自動推播訊息出去
	@Override
	public void onMessage( WebSocket conn, String message ) {
		this.sendToAll( message );
		System.out.println( conn + ": " + message );
	}

	@Override
	public void onMessage( WebSocket conn, ByteBuffer blob ) {
		conn.send( blob );
		System.out.println(new String(blob.array()));
	}
	//訊息發給全部的人
	public void sendToAll( String text ) {
		//有連進來的WebSocket
		Collection<WebSocket> con = connections();
		synchronized ( con ) {
			for( WebSocket c : con ) {
				c.send( text );
			}
		}
	}

}
